package com.sixbro.common.util;


import java.io.*;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.Certificate;
import java.util.Base64;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021/6/16 17:19
 */
public class ExportCertUtils {

    /**
     * 导出证书 base64格式
     *
     * @param keyStore
     * @param alias
     * @param exportFile
     * @throws Exception
     */
    public static void exportCert(KeyStore keyStore, String alias, String exportFile) throws Exception {
        Certificate certificate = keyStore.getCertificate(alias);
        String encoded = Base64.getEncoder().encodeToString(certificate.getEncoded());
        operation(encoded, exportFile, "------Begin Certificate-----", "-----End Certificate-----");
    }

    /**
     * 得到KeyPair
     *
     * @param keyStore
     * @param alias
     * @param password
     * @return
     */
    public static KeyPair getKeyPair(KeyStore keyStore, String alias, char[] password){
        try{
            Key key = keyStore.getKey(alias, password);
            if (key instanceof PrivateKey){
                Certificate certificate = keyStore.getCertificate(alias);
                PublicKey publicKey = certificate.getPublicKey();
                return new KeyPair(publicKey, (PrivateKey) key);
            }
        }catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 导出私钥
     *
     * @param privateKey
     * @param exportFile
     * @throws Exception
     */
    public static void exportPrivateKey(PrivateKey privateKey, String exportFile) throws Exception {
        String encoded = Base64.getEncoder().encodeToString(privateKey.getEncoded());
        operation(encoded, exportFile, "-----Begin Private Key-----", "-----End Private Key-----");
    }

    /**
     * 导出公钥
     *
     * @param publicKey
     * @param exportFile
     * @throws Exception
     */
    public static void exportPublicKey(PublicKey publicKey, String exportFile) throws Exception {
        String encoded = Base64.getEncoder().encodeToString(publicKey.getEncoded());
        operation(encoded, exportFile, "-----Begin Public Key-----", "-----End Public Key-----");
    }

    private static void operation(String source, String exportFile, String header, String footer) throws IOException {
        // Unicode的编码就是UTF-16，每个字符占两个字节，UTF-8每个字符占3个字节
        // 字节数组输入流
        InputStream in = new ByteArrayInputStream(source.getBytes(StandardCharsets.UTF_8));
        // 缓冲字节输出流
        OutputStream out = new FileOutputStream(exportFile);

        // 一次取出的字节数大小,缓冲区大小
        byte[] buffer = new byte[64];
        int len = -1;

        if (StringUtils.isNotBlank(header)) {
            // 非必须
            out.write(header.getBytes(StandardCharsets.UTF_8));
            out.write("\n".getBytes(StandardCharsets.UTF_8));
        }

        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
            out.write("\n".getBytes());
        }

        if (StringUtils.isNotBlank(footer)) {
            // 非必须
            out.write(footer.getBytes(StandardCharsets.UTF_8));
        }

        out.flush();
        in.close();
        out.close();
    }

    public static void main(String[] args) throws Exception{
        String keystoreFile = "C:\\App\\Workspace\\maven\\my\\spring-cloud-example\\spring-cloud-oauth2-example-03\\app-common\\app-common-security\\src\\main\\resources\\jwt.jks";
        // keystore的解析密码
        String keyStorePassword = "123456";

        String keyStoreType = "jks";
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(new FileInputStream(keystoreFile), keyStorePassword .toCharArray());

        // 条目别名
        String keyAlias = "jwt";
        // 条目的解析密码
        String keyPassword = "123456";
        String exportCertFile = "C:\\App\\Workspace\\maven\\my\\spring-cloud-example\\spring-cloud-oauth2-example-03\\app-common\\app-common-security\\src\\main\\resources\\cert.key";
        String exportPrivateFile = "C:\\App\\Workspace\\maven\\my\\spring-cloud-example\\spring-cloud-oauth2-example-03\\app-common\\app-common-security\\src\\main\\resources\\private.key";
        String exportPublicFile = "C:\\App\\Workspace\\maven\\my\\spring-cloud-example\\spring-cloud-oauth2-example-03\\app-common\\app-common-security\\src\\main\\resources\\public.key";

        ExportCertUtils.exportCert(keyStore, keyAlias, exportCertFile);
        // 注意这里的密码是你的别名对应的密码，不指定的话就是你的keystore的解析密码
        KeyPair keyPair = ExportCertUtils.getKeyPair(keyStore, keyAlias, keyPassword.toCharArray());
        ExportCertUtils.exportPrivateKey(keyPair.getPrivate(), exportPrivateFile);
        ExportCertUtils.exportPublicKey(keyPair.getPublic(), exportPublicFile);

        System.out.println("OK");
    }
}
